'use client'

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import type { ShareInfo } from '@/grpc/types';
import { SHARE_TARGET_TYPE } from '@/grpc/types';
import { IssuePanel } from '@/components/IssuePanel';
import { RequireMentPanel } from '@/components/RequireMentPanel';
import WorkPlanPanel from '@/components/WorkPlanPanel';
import { DrawPanel } from '@/components/DrawPanel';
import { DocPanel } from '@/components/DocPanel';

export default function Home() {
  const searchParams = useSearchParams()
  const id = searchParams.get("id") ?? "";
  const secret = searchParams.get("secret") ?? "";

  const [shareInfo, setShareInfo] = useState<ShareInfo | null>(null);
  const [errorMsg, setErrorMsg] = useState("");

  const loadShareInfo = async () => {
    const res = await fetch(`/api/share?id=${id}&secret=${secret}`);
    const resData = await res.json() as {
      code: number;
      errMsg: string;
      shareInfo: ShareInfo;
    };
    if (resData.code == 0) {
      setShareInfo(resData.shareInfo);
    } else {
      setErrorMsg(resData.errMsg);
    }
  }

  useEffect(() => {
    loadShareInfo();
  }, []);

  return (
    <main>
      {shareInfo == null && errorMsg != "" && errorMsg}
      {shareInfo != null && shareInfo.targetType == SHARE_TARGET_TYPE.SHARE_TARGET_TASK && (
        <IssuePanel shareInfo={shareInfo} />
      )}
      {shareInfo != null && shareInfo.targetType == SHARE_TARGET_TYPE.SHARE_TARGET_BUG && (
        <IssuePanel shareInfo={shareInfo} />
      )}
      {shareInfo != null && shareInfo.targetType == SHARE_TARGET_TYPE.SHARE_TARGET_REQUIRE_MENT && (
        <RequireMentPanel shareInfo={shareInfo} />
      )}
      {shareInfo != null && shareInfo.targetType == SHARE_TARGET_TYPE.SHARE_TARGET_WORK_PLAN && (
        <WorkPlanPanel shareInfo={shareInfo} />
      )}
      {shareInfo != null && shareInfo.targetType == SHARE_TARGET_TYPE.SHARE_TARGET_DRAW && (
        <DrawPanel shareInfo={shareInfo} />
      )}
      {shareInfo != null && shareInfo.targetType == SHARE_TARGET_TYPE.SHARE_TARGET_DOC && (
        <DocPanel shareInfo={shareInfo} />
      )}
    </main>
  );
}
